package com.jservice.web.sysUser;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jservice.framework.dto.Filter;
import com.jservice.framework.dto.Pageable;
import com.jservice.framework.dto.Pager;
import com.jservice.framework.idWorker.Sequence;
import com.jservice.framework.spring.SpringContextUtil;
import com.jservice.framework.utils.EncryptUtils;
import com.jservice.framework.utils.StringUtils;
import com.jservice.model.SysOffice;
import com.jservice.model.SysUser;
import com.jservice.model.SysUserRole;
import com.jservice.web.base.JBaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * UserQuery
 *
 * @author CWChen
 * @date 20170525
 */
@Service("sysUserQuery")
@Transactional(readOnly = true)
public class SysUserService extends JBaseService {

    public static final SysUser DAO = new SysUser();

    public static SysUserService me() {
        return SpringContextUtil.getBean("sysUserQuery");
    }

    @Resource
    private Sequence idWorker;

    public Pager findPage(Pageable pageable) {
        List<Filter> filters = pageable.getFilters();
//        filters.add(Filter.eq("su.supplier_type",  Setting.SupplierType.employee.name()));
        pageable.setFilters(filters);

        StringBuffer selectSql = new StringBuffer("select su.* , so.name as deptname ");
        StringBuffer whereSql = new StringBuffer();
        whereSql.append(" from ").append(SysUser.TABLE_NAME).append(" su ");
        whereSql.append(" left join ").append(SysOffice.TABLE_NAME).append(" so on so.id = su.department ");

        LinkedList<Object> paramValue = new LinkedList<Object>();

        fillFilters(whereSql,paramValue,pageable.getFilters());
        fillOrders(whereSql,pageable.getOrders());
        Page page = Db.paginate(pageable.getPageNumber(), pageable.getPageSize(), selectSql.toString(), whereSql.toString(), paramValue.toArray());
        Pager pager = new Pager(page.getList(),page.getTotalRow(),page.getTotalPage(),pageable);
        return pager;
    }

    public boolean usernameExists(String loginName) {
        if(loginName == null){
            return false;
        }
        SysUser sysUser = DAO.findFirst("select * from "+SysUser.TABLE_NAME+" where login_name = ? ",loginName);

        return sysUser != null;
    }

    @Transactional
    public boolean save(SysUser user, String[] roleIds) {
        if(user == null){
            return false;
        }

        user.setId(idWorker.nextIdStr());
        user.setCreateDate(new Date());
        user.setModifyDate(user.getCreateDate());
        user.save();


        user.putCache(user.getLoginName(),user);

        saveRoles(user.getId(),roleIds);

        return true;
    }

    @Transactional
    public boolean update(SysUser user, String[] roleIds) {
        if (user == null){
            return false;
        }
        user.setModifyDate(new Date());
        if(StringUtils.isNotBlank(user.getPassword())){
            user.setPassword(EncryptUtils.encryptPassword(user.getPassword(),user.getLoginName().substring(0,3)));
        }else{
            user.remove("password");
        }
        if(user.getIsEnabled() == null){
            user.setIsEnabled(Boolean.FALSE);
        }

        user.update();

        Db.deleteById(SysUserRole.TABLE_NAME,"user_id",user.getId());
        saveRoles(user.getId(),roleIds);

        return true;
    }

    private void saveRoles(String userId, String[]roleIds){
        if (roleIds != null){
            for(String roleId : roleIds){
                SysUserRole userRole = new SysUserRole();
                userRole.setId(idWorker.nextIdStr());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRole.save();
            }
        }
    }

    public Record findById(String userId) {
        String sql = "select ur.role_id from sys_user_role ur where ur.user_id = ?";
        List<String> roles = Db.query(sql,userId);
        Record user = Db.findFirst("select * from "+SysUser.TABLE_NAME+" where id = ? ",userId);
        user.set("roles",roles);
        return user;
    }

    @Transactional
    public boolean disableOrEnabled(String[] ids, Boolean isEnable){
        if(ids!= null  && ids.length > 0){
            String sql = "update "+SysUser.TABLE_NAME+" set is_enabled = ? where id in ( ";
            for(int index=0; index< ids.length ; index++){
                if(index > 0){
                    sql += ",";
                }

                sql += "'"+ids[index]+"'";
            }
            sql += ")";

            Db.update(sql,isEnable);
            return true;
        }
        return false;
    }

    public SysUser findByLoginName(String loginName){
        return DAO.doFindFirst("login_name = ?",loginName);
    }
}
